<?php

namespace App\Http\Controllers\Dashboard;

use App\Models\Area;
use App\Models\WebsiteCity;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;


class WebOrgController extends BaseController
{
    /**
     * 获取当前登录机构的机构树
     * @param Request $request
     * @return JsonResponse
     */
    public function tree(Request $request) {
        //只能展示自己有权限的菜单树
        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'tree' => getCityTree()
            ]
        ]);
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function save(Request $request) {

        $province_name = (string) $request->province_name;
        $city_name = (string) $request->city_name;


        $province_info =  Area::where('address_name','like',"%{$province_name}%")->where('address_type',1)->first();
        $city_info =  Area::where('address_name','like',"%{$city_name}%")->where('address_type',2)->first();

       if(!$province_info){
            return response()->json(['code' => 1, 'msg' => '省份未匹配上，请检查省份是否正确', 'data' => null]);
       }
        if(!$city_info){
            return response()->json(['code' => 1, 'msg' => '城市未匹配上，请检查城市是否正确', 'data' => null]);
        }

        if(WebsiteCity::where('org_code', $city_info->address_code)->exists()){
            return response()->json(['code' => 1, 'msg' => '城市已存在', 'data' => null]);
        }

        $WebsiteCity = WebsiteCity::where('org_code', $province_info->address_code)->first();

        if(!$WebsiteCity){
            $data = [
                'pid' => 0,
                'org_code' => $province_info->address_code,
                'name' => $province_info->address_name,
                'created_at' => date("Y-m-d H:i:s",time()),
            ];
            $pid = WebsiteCity::insertGetId($data);
        }else{
            $pid = $WebsiteCity->id;
        }
        $data = [
            'pid' => $pid,
            'org_code' => $city_info->address_code,
            'name' => $city_info->address_name,
            'created_at' => date("Y-m-d H:i:s",time()),
        ];
        WebsiteCity::insert($data);


        return response()->json([
            'code' => 0,
            'msg' => '保存成功',
            'data' => ''
        ]);


    }


}
